package devdocs

import org.joda.time.DateTime

class jqueryDatePickerTagLib {

def jqDatePicker = {attrs, body ->
	def out = out
	def name = attrs.name //The name attribute is required for the tag to work seamlessly with grails
	def id = attrs.id ?: name
	def minDate = attrs.minDate
	def showDay = attrs.showDay
	def value = attrs?.value
	
	//Create date text field and supporting hidden text fields need by grails
	out.println "<input type=\"text\" name=\"${name}\" id=\"${id}\" value=\"${formatDate(format:'dd/MM/yyyy',date:value)}\" />"
	out.println "<input type=\"hidden\" name=\"${name}_day\" id=\"${id}_day\" value=\"${formatDate(format:'dd',date:value)}\" />"
	out.println "<input type=\"hidden\" name=\"${name}_month\" id=\"${id}_month\" value=\"${formatDate(format:'MM',date:value)}\" />"
	out.println "<input type=\"hidden\" name=\"${name}_year\" id=\"${id}_year\" value=\"${formatDate(format:'yyyy',date:value)}\" />"
	
	//Code to parse selected date into hidden fields required by grails
	out.println "<script type=\"text/javascript\"> \$(document).ready(function(){"
	out.println "\$(\"#${id}\").datepicker({dateFormat: 'dd/mm/yy',"
	out.println "onClose: function(dateText, inst) {"
	out.println "\$(\"#${id}_month\").attr(\"value\",inst.selectedMonth +1);"
	out.println "\$(\"#${id}_day\").attr(\"value\",inst.selectedDay);"
	out.println "\$(\"#${id}_year\").attr(\"value\",inst.selectedYear);"
	out.println "}"
	
	//If you want to customize using the jQuery UI events add an if block an attribute as follows
	if(minDate != null){
		out.println ","
		out.println "minDate: ${minDate}"
	}
	
	if(showDay != null){
		out.println ","
		out.println "beforeShowDay: function(date){"
		out.println "var day = date.getDay();"
		out.println "return [day == ${showDay},\"\"];"
		out.println "}"
	}
	
	out.println "});"
	out.println "})</script>"
	
	}
}
